package validate

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gvalid"
)

// RuleRegisterAttachment 注册附件规则
func RuleRegisterAttachment() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`attach-id-exists`:  RuleAttachIdExists,
		`attach-exists-url`: RuleAttachExistsUrl,
	})
}

// RuleAttachIdExists 通过附件ID检测附件是否存在
func RuleAttachIdExists(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.IsEmpty() {
		return nil
	}
	// 附件ID是否存在
	if len(in.Value.String()) != 32 || !utils.AlphaNum(in.Value.String()) {
		return gerror.New(`附件ID格式错误`)
	}
	// 附件是否存在
	if ok := service.Attachment().CheckAttachmentExistsByAttachId(ctx, in.Value.String()); !ok {
		return gerror.New(`附件不存在`)
	}
	return nil
}

// RuleAttachExistsUrl 通过URL地址检测附件是否存在
func RuleAttachExistsUrl(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.IsEmpty() {
		return nil
	}
	// 附件URL是否存在
	if b, _ := service.Attachment().CheckAttachmentExists(ctx, g.Map{
		dao.Attachment.Columns().AttUrl: in.Value.String(),
	}); !b {
		return exception.Newf(`附件URl地址不存在，%s`, in.Message)
	}
	return nil
}
